package com.zy.springboot.service.book;

import com.alibaba.fastjson.JSONObject;
import com.zy.springboot.com.FastJsonConvert;
import com.zy.springboot.com.HttpUtil;
import com.zy.springboot.dao.book.BookDao;
import com.zy.springboot.dao.user.UserDao;
import com.zy.springboot.entity.user.UserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.zy.springboot.com.Const.PageConst;

/**
 * Created by y on 2019/1/11.
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class BookServiceImpl implements BookService {
    @Autowired
    private BookDao bookDao;
    @Autowired
    private UserDao userDao;
    private String APPID="wx528d836e30c593e6";
    private String SECRET="a87ac5b259bd0f49e1b1b0df6ac8842f";
    private static String get_oauth2_token_byCode = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=CODE&grant_type=authorization_code";

    @Override
    public JSONObject getBookList(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        //分页信息
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (jsonObject.containsKey("pageSize")) {
            pageSize = jsonObject.getInteger("pageSize");
        }
        if (jsonObject.containsKey("requestPage")) {
            requestPage = jsonObject.getInteger("requestPage");
        }
        //传参
        StringBuffer condition = new StringBuffer();
        String searchCondition=jsonObject.getString("searchCondition");
        String type=jsonObject.getString("type");
        List<Object> sqlArgs = new ArrayList<Object>();
        if (!StringUtils.isBlank(searchCondition)) {
           condition.append(" AND bookName like '%"+searchCondition+"%' or author like '%"+searchCondition+"%'");
        }
        if (!StringUtils.isBlank(type)) {
            condition.append(" AND grade = '"+type+"' ");
        }
        condition.append("AND DEL_FLAG=0");
        List<JSONObject> records=bookDao.getJSONListByPage(condition.toString(), sqlArgs.toArray(), requestPage, pageSize);
        Integer recordCount = records.size();
        int pageCount = 0;
        if (recordCount < pageSize) {
            pageCount = 1;
        } else {
            double flag = Math.ceil(recordCount / pageSize + 1);
            pageCount = ((int) flag);
        }
        if (recordCount == 0) {
            pageCount = 0;
        }

        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", records);
        return result;
    }

    @Override
    public JSONObject getBookById(String jsonData) {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String bookId=jsonObject.getString("bookId");
        return bookDao.getJSONById(bookId);
    }
    @Override
    public JSONObject getBookIndex (String jsonData)throws IOException {
        JSONObject jsonObject= FastJsonConvert.convertJSONToObject(jsonData,JSONObject.class);
        String bookId=jsonObject.getString("bookId");
        String openid=jsonObject.getString("openid");
        String index=jsonObject.getString("index");
        JSONObject book=bookDao.getJSONById(bookId);
        String downloadUrl=book.getString("downloadUrl");
        String type=book.getString("grade");
        List<String> list=new ArrayList<String>();
        String file="/usr/local/images/"+type+"/"+downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
        //String file="D:/images/txt/"+type+"/"+downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "GBK"); //或GB2312,GB18030
        BufferedReader fr = new BufferedReader(isr);
        //FileReader fr = new FileReader("D:/images/txt/武侠仙侠/《九鼎记》(bookbao.cc).txt");//FileReader 用于读文件
        BufferedReader br = new BufferedReader(fr);//使用缓冲区的方法将数据读入到缓冲区中
        String str;
        int i=1;
        int a=0,b=1;
        StringBuffer sql=new StringBuffer();
        while((str = br.readLine()) != null)
        {
            if(StringUtils.isBlank(str)){
                sql.append("\n");
            }else{
                sql.append(str);
                sql.append("\n");
            }
            if(i==a+PageConst)   //分页(以每PageConst个段落为一页)
            {
                list.add(sql.toString());
                sql.setLength(0);
                //System.out.println("------------------------  page "+b+"  ------------------------");
                a=a+PageConst;
                b=b+1;
            }
            i=i+1;
        }
        list.add(sql.toString());//文末不足PageConst行的也加进去为一页
        JSONObject result=new JSONObject();
        result.put("content",list.get(Integer.parseInt(index)-1));
        result.put("total",list.size());
        return  result;
    }
    @Override
    public JSONObject getOAuthTokenEntity(String code, UserEntity userEntity) {
        // 拼接请求地址
        String requestUrl = get_oauth2_token_byCode;
        requestUrl = requestUrl.replace("APPID", APPID);
        requestUrl = requestUrl.replace("SECRET", SECRET);
        requestUrl = requestUrl.replace("CODE", code);
        System.out.println(requestUrl);
        // 获取网页授权凭证
        JSONObject object = HttpUtil.request(requestUrl, "GET", null);
        String openid=object.getString("openid");
        String session_key=object.getString("session_key");
        userEntity.setDelFlag(0);
        userEntity.setOpenid(openid);
        userEntity.setSession_key(session_key);
        List<JSONObject> list= userDao.getJSONListByCondition( " AND openid=? ",new String[]{openid});

        if(!(list.size()>0)){
            userDao.add(userEntity);
        }
        return object;
    }
}
